import re
import hashlib


def safe_filename(original: str, max_length=256) -> str:
    '''
    用于将用例名称转化成可以设置成文件夹名称的字符串
    '''
    # 定义非法字符集（包含空格）
    illegal_chars = r'[\\/*?:<>|"$$$$ ]+'

    # Step 1: 替换所有非法字符为下划线
    cleaned = re.sub(illegal_chars, '_', original)

    # Step 2: 处理连续下划线
    normalized = re.sub(r'_{2,}', '_', cleaned)

    # Step 3: 去除首尾下划线
    normalized = normalized.strip('_')

    # Step 4: 添加哈希后缀保证唯一性 (6字符)
    unique_hash = hashlib.md5(original.encode()).hexdigest()[:6]

    # Step 5: 拼接基础名和哈希
    candidate = f"{normalized}_{unique_hash}" if normalized else unique_hash

    # Step 6: 长度限制处理
    if len(candidate) > max_length:
        core = normalized[:max_length - len(unique_hash) - 1]
        candidate = f"{core}_{unique_hash}"

    return candidate


# 测试用例
test_string = "test_login_success[http://localhost/-zenghuiming-Zhm@2009]"
print(safe_filename(test_string))  # 输出: test_login_success_localhost_zenghuiming-Zhm_da9f41